var websocket;
var m_list = [];	//消息列表
var ids = [];		//已经阅读过的消息时间戳

var date = new Date();
var is_bg_run = true;	//默认后台运行
var is_show_msg = true;	//默认通知

var msg_port;

function init(callback) {
	chrome.storage.local.get(function(obj){
		if(isNull(obj)){
			
		}else{
			if(obj.bg_run==false){
				is_bg_run = false;
			}else{
				is_bg_run = true;
			}

			if(obj.show_msg == false){
				is_show_msg = false;
			}else{
				is_show_msg = true;
			}
		}
		if(typeof(callback) == "function"){
			callback();
		}
	});
	getIDS();
}

function connectWS(callback) {
	var  wsServer = 'ws://chat.spsilab.cn/chat'; 
	// var  wsServer = 'ws://192.168.1.38:8000/chat'; 
	websocket = new WebSocket(wsServer); 
	websocket.onopen = function (evt) { onOpen(evt,callback) }; 
	websocket.onclose = function (evt) { onClose(evt) }; 
	websocket.onmessage = function (evt) { onMessage(evt) }; 
	websocket.onerror = function (evt) { onError(evt) }; 
}

function closeWS() {
	// console.log("websocket server close");
	websocket.close();
}

function onOpen(evt,callback) { 
	// console.log("websocket server open");
	if(is_bg_run)
		m_list.push(getMsg("<h3>Connect success</h3>"));
	if(typeof(callback) == "function"){
		callback();
	}
} 
function onClose(evt) { 
	if(is_bg_run)
		m_list.push(getMsg("<h3>Connect Closed</h3>"));
} 

function onError(evt) { 
	m_list.push(getMsg("<h3>Error:</h3>"+evt.data));
}

function onMessage(evt) { 
	//进行消息通知
	var data = evt.data;
	if(typeof(data) == "string")	//json
		data = JSON.parse(data);
	var isReaded = isRead(data);
	if(!isReaded){
		//当非后台运行时,每新开一个一个clien,server会重发一遍消息
		m_list.push(data);
		while(m_list.length > 30){
			m_list.shift();
		}
	}
	if(typeof(msg_port) != "undefined"){
		msg_port.postMessage({Msg:data});
	}
	if(is_show_msg){
		if(!isReaded){
			var opt = {
				type: "basic",
				title: "new message",
				message: data.user+":"+data.value,
				iconUrl: "images/icon.png"
			}

			// 然后显示通知。
			chrome.notifications.create(opt);
		}
	}
} 
//判断是否读过
function isRead(msg) {
	if (ids.lastIndexOf(msg.id) > -1) {
		//存在
		return true;
	}else{
		// ids.shift();	//移除第一个
		ids.push(msg.id);
		while(ids.length > 30){
			ids.shift();
		}
		saveIDS();	//保存
		return false;
	}
}

function saveIDS(){
	chrome.storage.local.set({"ids":ids});
}
function getIDS(){
	chrome.storage.local.get(function(obj){
		if(!isNull(obj) && typeof(obj.ids) != "undefined"){
			ids = obj.ids;
		}
	});
}

function getMsg(val){
	return Massage = {
			"value":val,
			"id":getTime(),
			"user":"Info",
			"htmlTime":getHtmlTime()
		}	
	}

function sendMessage(msg){
	if(typeof(msg)=="object"){
		var t = JSON.stringify(msg);
		// console.log("send:"+msg);
		// msg.user = "me";
		m_list.push(msg);
		websocket.send(t);//不符合规范不发送
	}
}

//获取时间,不包括日期
function getHtmlTime() {
	return "<span>"+date.toLocaleTimeString()+"<span>";
}

function getTime() {
	return date.getTime();
}

function showMessage(callback) {
	for (var m in m_list) {
		callback(m_list[m]);
	}
}
function isNull(obj) {
	for(var name in obj){
		return false;
	}
	return true;
}

chrome.runtime.onSuspend.addListener(function() {
		if(!is_bg_run){
			closeWS();
		}
});

chrome.runtime.onConnect.addListener(function(port) {
    // console.log(port.name == "popup");
    msg_port = port;
    port.onMessage.addListener(function(msg) {
	    //给popup发送消息
	    if(msg.Msg == "open"){
	    	if(is_bg_run){
	    		for (var m in m_list) {
						port.postMessage({Msg: m_list[m]});
				}
	    	}else{
	    		connectWS(function(){
	    			//connect success
	    			for (var m in m_list) {
						port.postMessage({Msg: m_list[m]});
					}
	    		});
	    	}
	    }else if(msg.Msg == "send"){
	    	// console.log("send");
	    	sendMessage(msg.value);
	    }
    });
    port.onDisconnect.addListener(function(){
    	// console.log("onDisconnect");
    	if(!is_bg_run){
    		closeWS();
    	}
    });
});
	//运行
	init(function(){
		if(is_bg_run){
			connectWS();
		}
	});